// api.js
import axios from 'axios';
import { getCookie, setCookie } from '../utils/common';
import router from '../router';

// 创建axios实例
const axiosInstance = axios.create({
  baseURL: "http://47.100.72.19:8888", // 服务器URL
  //baseURL: "http://127.0.0.1:8888", // 本地URL
  timeout: 10000, // 请求超时时间
  // 可以设置更多配置...
});


// 请求拦截器
axiosInstance.interceptors.request.use(config => {
  let token = getCookie("survey_user_token")
  console.log("token:"+token)
  if(token){
    config.headers['token'] = JSON.parse(token);
  }
  // 或者其他你需要设置的头部信息
  return config;
}, error => {
  return Promise.reject(error);
});
 
// 响应拦截器
axiosInstance.interceptors.response.use(response => {
  if(!response.data.flag && response.data.data === '403'){
    console.log("no token or token has bean expired!")
    setCookie("survey_user_token",'',0);
    router.push({path: '/'});
    return;
  }
  return response;
}, error => {
  // 对响应错误做点什么
  return Promise.reject(error);
});


export const getData = (url) => {
  return new Promise((resolve, reject) => {
    axiosInstance.get(url).then(response => {
          resolve(response.data);
      }).catch(error => {
        console.log(error)
          reject(error);
      });
  });
};

export const postData = (url, data) => {
  
  return new Promise((resolve, reject) => {
    axiosInstance.post(url, data).then(response => {
          resolve(response.data);
      }).catch(error => {
          reject(error);
      });
  });
};
export default axiosInstance;